import os
import shutil
import json5
from openpyxl.reader.excel import load_workbook


template_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '期末成绩汇总模版.xlsx')

with open('class1.json5', 'r',encoding='utf-8') as file:
    config_data = json5.load(file)

recharge_class = config_data.get('recharge_class')
if not recharge_class:
    recharge_class = dict()

def create_excel(outfile):
    dir_name = os.path.dirname(outfile)
    os.makedirs(dir_name, exist_ok=True)
    if not os.path.exists(outfile):
        shutil.copy(template_path, outfile)
        workbook = load_workbook(outfile)
        times = str(config_data.get('times') // 2)
        for sheet_name in workbook.sheetnames:
            if sheet_name.startswith('考勤成绩'):
                if sheet_name == '考勤成绩'+times:
                    workbook['考勤成绩' + times].title = '考勤成绩'
                else:
                    sheet_to_delete = workbook[sheet_name]
                    workbook.remove(sheet_to_delete)
        workbook.save(outfile)
    return outfile

def delete_empty_rows(worksheet, start_row, keep_row=30):
    rows_to_delete = []
    for index, row in enumerate(worksheet.iter_rows(), start=1):
        # 检查第一列的值是否为 'delete'
        if index < start_row:
            continue
        if row[1].value is None:   # 学号为None
            rows_to_delete.append(index)
    # 为避免删除行时索引变化导致的问题，从后往前删除
    for row_index in reversed(rows_to_delete):
        if row_index > keep_row + start_row - 1:
            worksheet.delete_rows(row_index)
        # print(row_index)